import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators, AbstractControl } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';

// services
import { ConstantService } from '../../../../../core/services/constant.service';
import { ServerService } from '../../../../../core/services/server.service';
import { StorageService } from '../../../../../core/services/storage.service';

@Component({
    selector: 'app-subject-management',
    templateUrl: './subject-management.component.html',
    styleUrls: ['./subject-management.component.css']
})
export class SubjectManagementComponent implements OnInit {
    subjectForm: FormGroup;             // 科目表单
    isVisible: boolean = false;         // 是否显示modal
    isConfirmLoading: boolean = false;  // modal中点击保存的时候的过渡效果
    isViewStateUpdate: boolean = false; // 页面是否是更新状态
    subjectList: object[] = [];         // 全部科目列表
    schoolId: string;                   // 学校id
    _current: number = 1;               // 当前页
    _pageSize: number = 10;             // 每页数量
    _total: number = 1;                 // 数据总数
    _loading: boolean = true;           // 加载动画

    constructor(
        private fb: FormBuilder,
        private constant: ConstantService,
        private server: ServerService,
        private storage: StorageService,
        private message: NzMessageService
    ) {
        /**
         * 初始化学科表单
         * 学科名称: name
         */
        this.subjectForm = this.fb.group({
            _id: [null],
            name: [null, [Validators.required, Validators.maxLength(10)]]
        });
        this.schoolId = this.storage.getItem(this.constant.storage.currentUser)['schoolId']['_id'];
    }

    ngOnInit() {
        this.getAllSubjects();
    }

    /**
     * 显示modal,添加或更新年级信息
     * @param id 
     */
    async showModal(id) {
        this.isVisible = true;
        if (id) {
            this.isViewStateUpdate = true;
            const result = await this.server.fetch(this.constant.api.manage.subject.findOne, { id });
            if (result) {
                this.subjectForm.controls._id.setValue(result.data._id);
                this.subjectForm.controls.name.setValue(result.data.name);
            }
        } else {
            this.isViewStateUpdate = false;
            this.subjectForm.reset();
        }
    }

    // 获取表单项
    getFormControl(name): AbstractControl {
        return this.subjectForm.controls[name];
    }

    /**
     * 保存 || 更新
     * @param e 
     * @param school 
     */
    async handleOk(e, subject): Promise<void> {
        subject.schoolId = this.schoolId;
        this.isConfirmLoading = true;
        // 保存
        const result = await this.server.fetch(this.constant.api.manage.subject[this.isViewStateUpdate ? 'update' : 'save'], subject);
        if (result) {
            this.message.success('保存科目成功');
            if (!this.isViewStateUpdate) {
                // 清空表单
                this.subjectForm.reset();
            } else {
                this.isVisible = false;
            }
            this.isConfirmLoading = false;
            this.getAllSubjects();
        } else {
            this.isConfirmLoading = false;
        }

    }

    /**
     * 关闭modal
     * @param e 
     */
    handleCancel(e): void {
        this.isVisible = false;
    }

    /**
     * 获取全部年级列表
     */
    async getAllSubjects(): Promise<void> {
        const param = {
            schoolId: this.schoolId,
            limit: this._pageSize
        };
        if (this._current !== 1) {
            param['date'] = this.subjectList[this.subjectList.length - 1]['createDate'];
        }
        const allSubjects = await this.server.fetch(this.constant.api.manage.subject.findAll, param);
        if (allSubjects) {
            this.subjectList = allSubjects.data.data;
            this._total = allSubjects.data.count;
            this._loading = false;
        } else {
            this._loading = false;
        }
    }

}
